<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      label-position="left"
    >
      <el-form-item
        :label="$t('form.evaluation.nickname')"
        prop="appraiseUserId"
      >
        <el-input
          v-model="queryParams.nickName"
          :placeholder="$t('form.evaluation.enterUserNickname')"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item
        :label="$t('form.evaluation.notificationStatus')"
        prop="noticeStatus"
      >
        <el-select
          v-model="queryParams.noticeStatus"
          :placeholder="$t('form.evaluation.selectNotificationStatus')"
          clearable
        >
          <el-option
            :value="1"
            :label="$t('form.evaluation.sent')"
          ></el-option>
          <el-option
            :value="0"
            :label="$t('form.evaluation.notSent')"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('form.evaluation.evaluationStatus')"
        prop="nickName"
      >
        <el-select
          v-model="queryParams.reviewerStatus"
          :placeholder="$t('form.evaluation.selectEvaluationStatus')"
          clearable
        >
          <el-option
            :value="1"
            :label="$t('form.evaluation.evaluated')"
          ></el-option>
          <el-option
            :value="0"
            :label="$t('form.evaluation.notEvaluated')"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="ele-Search"
          @click="handleQuery"
        >
          {{ $t("common.search") }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="ele-Grid"
          @click="handleShowScoreDetail"
        >
          {{ $t("form.evaluation.scoreDetails") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="ele-Grid"
          @click="handleShowScoreSummary"
        >
          {{ $t("form.evaluation.totalScoreTable") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="ele-Promotion"
          @click="showConfigTemplate"
        >
          {{ $t("form.evaluation.sendNotification") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="ele-Download"
          @click="handleDownloadQrcode"
        >
          {{ $t("form.evaluation.downloadQRCode") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="ele-Delete"
          :disabled="multiple"
          @click="handleCleanData"
        >
          {{ $t("form.evaluation.clearData") }}
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="ele-Download"
          @click="handleExport"
        >
          {{ $t("common.export") }}
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @query-table="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="evalReviewerList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        :label="$t('form.evaluation.evaluator')"
        align="center"
        prop="reviewerUserId"
      >
        <template #default="scope">
          <t-avatar
            :size="30"
            :url="scope.row.reviewerUser!.avatar"
            :name="scope.row.reviewerUser.nickName"
          ></t-avatar>
          {{ scope.row.reviewerUser!.nickName }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('form.evaluation.notificationStatus')"
      >
        <template #default="scope">
          <el-tag
            v-if="scope.row.noticeStatus === 1"
            type="success"
          >
            {{ $t("form.evaluation.notified") }}
          </el-tag>
          <el-tag
            v-else
            type="danger"
          >
            {{ $t("form.evaluation.notNotified") }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('form.evaluation.evaluationStatus')"
      >
        <template #default="scope">
          <el-tag
            v-if="scope.row.reviewerStatus === 1"
            type="success"
          >
            {{ $t("form.evaluation.evaluated") }}
          </el-tag>
          <el-tag
            v-else
            type="danger"
          >
            {{ $t("form.evaluation.notEvaluated") }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('form.evaluation.evaluate')"
      >
        <template #default="scope">
          <span
            v-for="(re, index) in scope.row.appraiseUserList"
            :key="re.userId + re.roleId"
          >
            <el-tag
              size="small"
              class="ml6"
              v-if="index < 2"
            >
              {{ re?.user?.nickName }}
            </el-tag>
          </span>
          <el-link
            class="ml10"
            type="primary"
            @click="handleShowUserInfo(scope.row.appraiseUserList)"
          >
            {{ $t("form.evaluation.details") }}({{ scope.row.appraiseUserList!.length }})
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('form.evaluation.operation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="ele-Share"
            @click="handleShowShareDialog(scope.row)"
          >
            {{ $t("form.evaluation.share") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.current"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <el-dialog
      :title="$t('form.evaluation.userDetails')"
      v-model="userInfoVisible"
      width="700px"
      append-to-body
    >
      <el-table :data="currentRoleUserList">
        <el-table-column
          prop="nickName"
          :label="$t('form.evaluation.nickname')"
          align="center"
          width="180"
        >
          <template #default="scope">
            <t-avatar
              :size="30"
              :url="scope.row!.avatar"
              :name="scope.row.nickName"
            ></t-avatar>
            <span>{{ scope.row!.nickName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          :label="$t('form.evaluation.account')"
          align="center"
          width="180"
        />
        <el-table-column
          prop="phonenumber"
          :label="$t('form.evaluation.phoneNumber')"
          align="center"
        />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userInfoVisible = false">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="$t('form.evaluation.share')"
      v-model="shareVisible"
      width="700px"
      append-to-body
    >
      <url-operate :link-url="shareUrl" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="shareVisible = false">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="$t('form.evaluation.scoreDetails')"
      v-model="scoreDetailVisible"
      width="900px"
      append-to-body
    >
      <el-button
        type="primary"
        plain
        icon="ele-Download"
        class="mb10"
        @click="handleExportDetailScore"
      >
        {{ $t("common.export") }}
      </el-button>
      <el-table :data="scoreDetailList">
        <el-table-column
          prop="score"
          :label="$t('form.evaluation.score')"
          align="center"
        />
        <el-table-column
          prop="reviewerName"
          :label="$t('form.evaluation.evaluator')"
          align="center"
        />
        <el-table-column
          prop="evaluatedName"
          :label="$t('form.evaluation.evaluatePerson')"
          align="center"
        />
        <el-table-column
          prop="reviewerRole"
          :label="$t('form.evaluation.evaluationRole')"
          align="center"
        />
        <el-table-column
          prop="formItemName"
          :label="$t('form.evaluation.question')"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ removeHtmlTag(scope.row.formItemName) }}
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="scoreDetailTotal > 0"
        :total="scoreDetailTotal"
        v-model:page="scorePageParams.current"
        v-model:limit="scorePageParams.size"
        @pagination="getListScoreDetail"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="scoreDetailVisible = false">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="$t('form.evaluation.totalScoreTable')"
      v-model="scoreSummaryVisible"
      width="900px"
      append-to-body
    >
      <el-button
        type="primary"
        plain
        icon="ele-Download"
        @click="handleExportSummaryScore"
        class="mb10"
      >
        {{ $t("common.export") }}
      </el-button>
      <el-table :data="scoreSummaryList">
        <el-table-column
          prop="nickName"
          :label="$t('form.evaluation.evaluatePerson')"
          align="center"
        />
        <el-table-column
          prop="score"
          :label="$t('form.evaluation.score')"
          align="center"
        />
      </el-table>
      <pagination
        v-show="scoreSummaryTotal > 0"
        :total="scoreSummaryTotal"
        v-model:page="scoreSummaryPageParams.current"
        v-model:limit="scoreSummaryPageParams.size"
        @pagination="getListScoreSummary"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="scoreSummaryVisible = false">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <config-template
      ref="configTemplateRef"
      :fields="msgConfigFields"
      :title="$t('form.evaluation.sendNotification')"
      @submit="handleSendNotice"
    />
  </div>
</template>

<script setup name="EvalReviewer" lang="ts">
import { clearData, EvalReviewer, exportReviewer, listEvalReviewer, NoticeParam, sendNotify } from "@/api/evaluation/reviewer";
import { ref } from "vue";
import { MessageBoxUtil, MessageUtil } from "@/utils/messageUtil";
import { i18n } from "@/i18n";
import { useRoute } from "vue-router";
import TAvatar from "@/components/TAvatar/index.vue";
import { UserEntity } from "@/api/system/user";
import UrlOperate from "@/views/form/publish/UrlOperate.vue";
import { getBaseUrlPath } from "@/utils/auth";
import ConfigTemplate from "@/views/form/publish/TodoForm/ConfigTemplate.vue";
import { FieldItem } from "@/api/project/form";
import { download, formatString } from "@/utils/tduck";
import { getExtSettingByType, saveExtSetting } from "@/api/project/extSetting";
import { removeHtmlTag } from "@/views/formgen/utils";
import { useFormInfo } from "@/stores/formInfo";
import { storeToRefs } from "pinia";
import {
  EvalScoreDetails,
  exportQrcode,
  exportScoreDetails,
  exportScoreSummary,
  listEvalScoreDetails,
  listEvalScoreSummary
} from "@/api/evaluation/score";

const evalReviewerList = ref<EvalReviewer[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const userInfoVisible = ref(false);

const route = useRoute();

const queryParams = ref<any>({
  current: 1,
  size: 10,
  nickName: "",
  noticeStatus: undefined,
  reviewerStatus: undefined,
  formKey: route.query.key as string
});

/** 查询评价人列表 */
const getList = () => {
  loading.value = true;
  listEvalReviewer(queryParams.value).then(response => {
    evalReviewerList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.current = 1;
  getList();
};

// 多选框选中数据
const handleSelectionChange = (selection: EvalReviewer[]) => {
  ids.value = selection.map((item: EvalReviewer) => item.id || 0);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 导出按钮操作 */
const handleExport = () => {
  exportReviewer(queryParams.value).then((res: any) => {
    download(res, i18n.global.t("form.evaluation.evaluatorListFile", { no: new Date().getTime() }));
  });
};

getList();

const currentRoleUserList = ref<UserEntity[]>([]);

const handleShowUserInfo = (appraiseUserList: any[]) => {
  userInfoVisible.value = true;
  currentRoleUserList.value = appraiseUserList!.map(item => item.user) || [];
};

const shareVisible = ref(false);
const shareUrl = ref("");

const handleShowShareDialog = (row: EvalReviewer) => {
  shareVisible.value = true;
  shareUrl.value = `${getBaseUrlPath()}/e/${row.reviewerKey}`;
};

const configTemplateRef = ref<any>(null);

const showConfigTemplate = () => {
  getExtSettingByType("evalNoticeMsgTemplate", route.query.key as string).then(res => {
    configTemplateRef.value!.show(res.data?.settings ? JSON.parse(res.data.settings) : {});
  });
};

const msgConfigFields = ref<FieldItem[]>([
  {
    label: i18n.global.t("form.evaluation.evaluationLink"),
    value: "link"
  },
  {
    label: i18n.global.t("form.evaluation.nickname"),
    value: "userNickName"
  },
  {
    label: i18n.global.t("form.evaluation.evaluationName"),
    value: "formName"
  },
  {
    label: i18n.global.t("form.evaluation.evaluationId"),
    value: "evalId"
  }
]);

const formInfoStore = useFormInfo();
const { currentFormName } = storeToRefs(formInfoStore);

const handleSendNotice = async (val: any) => {
  if (undefined === val.templateId) {
    return;
  }
  await saveExtSetting({
    formKey: route.query.key as string,
    settings: JSON.stringify(val),
    type: "evalNoticeMsgTemplate"
  });

  const data: NoticeParam = {
    formKey: route.query.key as string,
    params: {
      formName: removeHtmlTag(currentFormName.value),
      link: getBaseUrlPath() + "/e/"
    }
  };
  if (ids.value && ids.value.length) {
    data.reviewerIds = ids.value;
  } else {
    data.all = true;
  }
  const msg =
    ids.value && ids.value.length
      ? i18n.global.t("form.evaluation.confirmSendNotificationToSelected", { num: ids.value.length })
      : i18n.global.t("form.evaluation.confirmSendNotificationToAll");
  MessageBoxUtil.confirm(
    msg,
    () => {
      sendNotify(data).then(() => {
        MessageUtil.success(i18n.global.t("form.evaluation.sendSuccess"));
      });
    },
    i18n.global.t("form.evaluation.prompt")
  );
};

const scoreDetailVisible = ref(false);

const scoreDetailList = ref<EvalScoreDetails[]>([]);
const scoreDetailTotal = ref(0);
const scorePageParams = ref<any>({
  current: 1,
  size: 10,
  formKey: route.query.key as string
});

const handleShowScoreDetail = () => {
  scoreDetailVisible.value = true;
  getListScoreDetail();
};

const getListScoreDetail = () => {
  listEvalScoreDetails(scorePageParams.value).then(res => {
    scoreDetailList.value = res.data.records;
    scoreDetailTotal.value = res.data.total;
  });
};

const handleCleanData = () => {
  MessageBoxUtil.confirm(i18n.global.t("form.evaluation.confirmClearSelectedEvaluatorData"), () => {
    clearData(route.query.key as string, ids.value).then(() => {
      MessageUtil.success(i18n.global.t("form.evaluation.clearSuccess"));
      getList();
    });
  });
};

const scoreSummaryVisible = ref(false);

const scoreSummaryList = ref<EvalScoreDetails[]>([]);
const scoreSummaryTotal = ref(0);
const scoreSummaryPageParams = ref<any>({
  current: 1,
  size: 10,
  formKey: route.query.key as string
});

const handleShowScoreSummary = () => {
  scoreSummaryVisible.value = true;
  getListScoreSummary();
};

const getListScoreSummary = () => {
  listEvalScoreSummary(scoreSummaryPageParams.value).then(res => {
    scoreSummaryList.value = res.data.records;
    scoreSummaryTotal.value = res.data.total;
  });
};

const handleExportDetailScore = () => {
  exportScoreDetails(queryParams.value).then((res: any) => {
    download(res, i18n.global.t("form.evaluation.scoreDetailsFile", { no: new Date().getTime() }));
  });
};

const handleExportSummaryScore = () => {
  exportScoreSummary(queryParams.value).then((res: any) => {
    download(res, i18n.global.t("form.evaluation.totalScoreTableFile", { no: new Date().getTime() }));
  });
};

const handleDownloadQrcode = () => {
  exportQrcode(queryParams.value).then((res: any) => {
    download(res, i18n.global.t("form.evaluation.evaluationQRCode", { no: new Date().getTime() }), ".docx");
  });
};

defineExpose({
  getList
});
</script>
